package com.ruoyi.common.utils.aop;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 *
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {

    private long start;
    private long end;

    @Pointcut("execution(public * com.ruoyi..controller.*.*(..))")
    public void controllerWebLog() {

    }


    @Before("controllerWebLog()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("");
        log.info("");
        log.info("《================================================================请求开始================================================================》");
        start = System.currentTimeMillis();
        log.info("URL :             " + request.getRequestURL().toString());
        log.info("HTTP_METHOD :     " + request.getMethod());
        log.info("IP :              " + request.getRemoteAddr());
        log.info("CLASS_METHOD :    " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS:         " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "res", pointcut = "controllerWebLog()")
    public void doAfterReturning(Object res) throws JsonProcessingException {
        log.info("RESPONSE :        " + new ObjectMapper().writeValueAsString(res));
        end = System.currentTimeMillis();
        log.info("响应时间 :  {} 毫秒", end - start);
        log.info("《================================================================请求结束================================================================》");
    }
}
